package com.gzc.just.play.last.war.sceneserver.handler;

import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.sceneserver.battle.BattleManager;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 战斗列表处理器
 * 处理获取战斗列表的消息
 */
@Component
public class BattleListHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(BattleListHandler.class);
    
    @Autowired
    private BattleManager battleManager;
    
    private static final int BATTLE_LIST = 1006;
    
    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        // 从上下文中获取玩家ID
        io.netty.util.AttributeKey<Long> playerIdKey = io.netty.util.AttributeKey.valueOf("playerId");
        Long playerId = ctx.channel().attr(playerIdKey).get();
        if (playerId == null) {
            logger.error("Player ID not found in context, cannot process battle list message");
            return;
        }
        
        // 获取战斗列表
        List<Map<String, Object>> battleList = battleManager.getBattleList();
        
        // 发送战斗列表响应
        sendBattleListResponse(ctx, battleList, true, "Battle list retrieved successfully");
        
        logger.info("Player {} requested battle list, returning {} battles", playerId, battleList.size());
    }
    
    private void sendBattleListResponse(ChannelHandlerContext ctx, List<Map<String, Object>> battleList, 
                                      boolean success, String message) {
        // 实际实现中应该构造并发送战斗列表响应消息
        logger.info("Sending battle list response: success={}, message={}, battleCount={}", 
                   success, message, battleList.size());
        
        // 示例：打印战斗列表内容（实际实现中应该将列表序列化为响应消息）
        if (success && !battleList.isEmpty()) {
            logger.debug("Battle list content:");
            for (Map<String, Object> battle : battleList) {
                logger.debug("Battle ID: {}, Name: {}, Status: {}, Player Count: {}", 
                           battle.get("battleId"), 
                           battle.get("name"), 
                           battle.get("status"), 
                           battle.get("playerCount"));
            }
        }
    }

    @Override
    public int getMessageId() {
        return BATTLE_LIST;
    }
    
    @Override
    public String getName() {
        return "BattleListHandler";
    }
    
    @Override
    public Logger getLogger() {
        return logger;
    }
}